//
//  IDCardAuthenticationViewController.m
//  NiuBanJinGold
//
//  Created by Billy on 15/10/19.
//  Copyright © 2015年 zzjr. All rights reserved.
//

#import "IDCardAuthenticationViewController.h"
#import "BankCardBindingViewController.h"

@interface IDCardAuthenticationViewController ()

@property (nonatomic, strong) UIView *view_header;
@property (nonatomic, strong) UIView *view_center;
@property (nonatomic, strong) NSMutableDictionary *mutableDic_text;

@property (nonatomic , strong) NSArray *array_type;
@end

@implementation IDCardAuthenticationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.array_type = @[@"继续存入" , @"返回安全中心"];
    [self pageSettingsAndSubviewsCreation];
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    if ([[UserManager sharedUserManager] isAuthentication]) { //如果验证直接到ROOTVIEWcontroller
        
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}

#pragma mark - SubviewsCreationAndPageSettings

- (void) pageSettingsAndSubviewsCreation {
    
    [self.navigationItem setTitle:@"实名认证"];
    
    [self.view setBackgroundColor:BASECOLOR];
    
    [self.view addSubview:self.view_header];
}


#pragma mark - setter methods

- (UIView *)view_center {
    
    if (!_view_center) {
        
        _view_center = [UsefulUtil viewCreationWithFrame:CGRectMake(0, MULTIPLYHEIGHT(40.0/2), SCREEN_WIDTH, MULTIPLYHEIGHT(400.0/2)) backgroundColor:[UIColor whiteColor] backGroundImage:nil];
        
        // 添加label/textfield
        for (int i = 0; i < 4; i ++) {
            
            UILabel *label_title = [UsefulUtil labelCreationWithFrame:CGRectMake(MULTIPLYWIDTH(30.0/2), MULTIPLYHEIGHT(36.0/2) + i *MULTIPLYHEIGHT(100.0/2), MULTIPLYWIDTH(180.0/2), MULTIPLYHEIGHT(30.0/2)) textColor:[UsefulUtil colorWithHexString:@"#434343"] fontName:[UIFont systemFontOfSize:15.0] text:self.mutableDic_text[@"title"][i]];
            
            [_view_center addSubview:label_title];
            
            
            BCTextField *textFiled_tmp = [[BCTextField alloc] initWithFrame:CGRectMake(MULTIPLYWIDTH(20.0/2) + CGRectGetMaxX(label_title.frame), i * MULTIPLYHEIGHT(99.0/2), SCREEN_WIDTH - MULTIPLYWIDTH(20.0/2)- CGRectGetMaxX(label_title.frame)  , MULTIPLYHEIGHT(99.0/2))];
            [textFiled_tmp setTag:(i  +50)];
            
            [textFiled_tmp setPlaceholder:self.mutableDic_text[@"placeHolder"][i] ];
            
            if (i == 0) {
                
//               [textFiled_tmp setRegx:@"^[\u4e00-\u9fa5]{0,}$"]; //第一个是中文姓名
            }else if(i ==1){
                
                //规则是15或18位[18位的最后一位是x]
                
               [textFiled_tmp setRegx:@"^[0-9]{0,18}+([xX]{1})?$"]; //身份证
                
            } else if(i == 2 || i  ==3){
                
                [textFiled_tmp setKeyboardType:UIKeyboardTypeNumberPad];
                [textFiled_tmp setRegx:@"^[0-9]{1,6}$"]; //数字密码
                [textFiled_tmp setSecureTextEntry:YES];
            }
            
            
            [_view_center addSubview:textFiled_tmp];
            
            
            UIView *view_sep = [UsefulUtil viewCreationWithFrame:CGRectMake(0, (i +1 ) * MULTIPLYHEIGHT(99.0/2), SCREEN_WIDTH, MULTIPLYHEIGHT(1.0/2)) backgroundColor:[UsefulUtil colorWithHexString:@"#c7c7cd"] backGroundImage:nil];
            
            [_view_center addSubview:view_sep];
        }
    }
    
    return _view_center;
}

- (UIView *)view_header {
    
    if (!_view_header) {
        
        _view_header = [UsefulUtil viewCreationWithFrame:CGRectMake(0,0, SCREEN_WIDTH, MULTIPLYHEIGHT((490.0 +62.0+90.0+28.0+30.0+16.0+60.0)/2)) backgroundColor:BASECOLOR backGroundImage:nil];
        
        UIView *view_top = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, MULTIPLYHEIGHT(40.0/2))];
        [view_top setBackgroundColor:BASECOLOR];
        
        [_view_header addSubview:view_top];
        
        [_view_header addSubview:self.view_center];
        
        //提示奖励
        
        NSString *str_promt = @"认证成功可获得蓝色加息券一张和500积分";
        UILabel *label_prompt = [UsefulUtil labelCreationWithFrame:CGRectMake(MULTIPLYWIDTH(30.0/2), CGRectGetMaxY(self.view_center.frame) + MULTIPLYHEIGHT(20.0/2), SCREEN_WIDTH - MULTIPLYWIDTH(60.0/2), MULTIPLYHEIGHT(30.0/2)) textColor:[UsefulUtil colorWithHexString:@"#b3b3b3"] fontName:[UIFont systemFontOfSize:11.0] text:str_promt];

        
        NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:str_promt];
        
        [attrStr addAttribute:NSForegroundColorAttributeName value:REDCOLOR range:NSMakeRange(7, 5)];
        [attrStr addAttribute:NSForegroundColorAttributeName value:REDCOLOR range:NSMakeRange(15, 5)];

        [label_prompt setAttributedText:attrStr];
        
        [_view_header addSubview:label_prompt];
        
        //button
        
        UIButton *button_authentication = [UsefulUtil buttonCreationWithFrame:CGRectMake(MULTIPLYWIDTH(30.0/2), CGRectGetMaxY(label_prompt.frame) + MULTIPLYHEIGHT(62.0/2), SCREEN_WIDTH - MULTIPLYWIDTH(60.0/2), MULTIPLYHEIGHT(90.0/2)) textColor:[UIColor whiteColor] fontName:[UIFont systemFontOfSize:14.0] text:@"认证"];

        [button_authentication addTarget:self action:@selector(authenticationButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
        [button_authentication setBackgroundColor:REDCOLOR];
        
        [_view_header addSubview:button_authentication];
        
        // 温馨提示
        
        UIImageView *imageView = [UsefulUtil imageViewCreationWithFrame:CGRectMake(MULTIPLYWIDTH(30.0/2), CGRectGetMaxY(button_authentication.frame) + MULTIPLYHEIGHT(28.0/2), MULTIPLYWIDTH(23.0/2), MULTIPLYWIDTH(20.0/2)) image:[UIImage imageNamed:@"heart"]];
        
        [_view_header addSubview:imageView];
        
        
        UILabel *label_promptMiddle = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(imageView.frame), imageView.frame.origin.y - MULTIPLYHEIGHT(4.0/2), MULTIPLYWIDTH(240.0/2), MULTIPLYHEIGHT(30.0/2))];
        
        [label_promptMiddle setTextColor:[UsefulUtil colorWithHexString:@"#989898"]];
        [label_promptMiddle setText:@"温馨提示"];
        [label_promptMiddle setFont:[UIFont systemFontOfSize:11.0]];
        [_view_header addSubview:label_promptMiddle];
        
        //最下面的
        UILabel *label_promptBottom = [UsefulUtil labelCreationWithFrame:CGRectMake(MULTIPLYWIDTH(30.0/2), CGRectGetMaxY(label_promptMiddle.frame) + MULTIPLYHEIGHT(16.0/2), SCREEN_WIDTH - MULTIPLYWIDTH(60.0/2), MULTIPLYHEIGHT(60.0/2)) textColor:[UsefulUtil colorWithHexString:@"#989898"] fontName:[UIFont systemFontOfSize:11.0] text:@"为保证您牛钱包的收益和保护您账号的安全,需要您设置实名信息和转出密码"];
        [label_promptBottom setNumberOfLines:0];
        [_view_header addSubview:label_promptBottom];
        
    }
    return _view_header;
}

- (NSMutableDictionary *)mutableDic_text {
    
    if (!_mutableDic_text) {
        
        _mutableDic_text = [NSMutableDictionary dictionary];
        
        [_mutableDic_text setObject:@[@"持卡人姓名",@"身份证号",@"设置转出密码",@"再次设置密码"] forKey:@"title"];
        [_mutableDic_text setObject:@[@"请输入姓名",@"请输入18位身份证号",@"请输入6位转出密码",@"请重复6位转出密码"] forKey:@"placeHolder"];
    }
    
    return _mutableDic_text;
}

#pragma mark - button events handing

- (void) authenticationButtonClicked: (UIButton *) button {
    
    [self.view endEditing:YES];
    
    // 取得用户姓名，身份证号等。
    
    BCTextField* textfiled_name = [self.view_center viewWithTag:50];
    BCTextField* textfiled_IDCard = [self.view_center viewWithTag:51];
    BCTextField* textfiled_password = [self.view_center viewWithTag:52];
    BCTextField* textfiled_password_Retype = [self.view_center viewWithTag:53];
    
    if (![UsefulUtil isChinese:textfiled_name.text]) {
        
        [UsefulUtil showAlertView:@"请输入中文姓名"];
        return;
    }else if([UsefulUtil isIDNumber:textfiled_IDCard.text] == NO){
        
        [UsefulUtil showAlertView:@"请输入正确的身份证号"];
        return;
    }else if([textfiled_password.text isEqualToString:@""] || [textfiled_password_Retype.text isEqualToString:@""]){
        
        [UsefulUtil showAlertView:@"密码不能为空!"];
        return;
    }else if(![textfiled_password.text isEqualToString:textfiled_password_Retype.text]){
        
        [UsefulUtil showAlertView:@"密码二次输入不一致!"];
        return;
    }else {
        
        NSDictionary *dic_params = @{@"userId": [UserManager sharedUserManager].user.user_userId,
                                     @"realname":textfiled_name.text
                                     ,@"idNumber":textfiled_IDCard.text,@"tradePassword":textfiled_password.text};
        
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        
        [[NetworkUtil sharedNetworkUtil] zzjrUserRealNameAuthenticationByParmeteres:dic_params transferResultUsingBlock:^(id parsedData, NSError *error) {
            
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
  
            NSDictionary *dic_result = parsedData;
            
            if ([dic_result[@"status"] integerValue] == 0) {
                
                // update local user info
                
                User *user = [UserManager sharedUserManager].user;
                
                [user setUser_isRealNameAuthentication:[NSNumber numberWithBool:YES]];
                [user setUser_userRealName:dic_result[@"result"][@"realname"]];
                
                [[UserManager sharedUserManager] saveCurrentUser:user];
                
                
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:dic_result[@"result"][@"contents"] message:nil delegate:self cancelButtonTitle:self.array_type[self.Type] otherButtonTitles:nil, nil];
                [alert show];

            }else {
                
                [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
                [UsefulUtil showAlertView:dic_result[@"msg"]];
            }
        }];
    }
    
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    
    switch (buttonIndex) {
        case 0:
        {
            
            if (self.Type != 0) {
                
                [self.navigationController popViewControllerAnimated:YES];
            }else {
                
                //跳到绑定存入page
                BankCardBindingViewController *bankVC = [[BankCardBindingViewController alloc] init];
                [bankVC setHidesBottomBarWhenPushed:YES];
                [self.navigationController pushViewController:bankVC animated:YES];
                
                }
            }  break;
            default:
            break;
       
    }
}


// keep this method as empty
- (void) swiperGestureHandle:(UISwipeGestureRecognizer *) swipe {

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
